package com.sudo.api.interceptor;

import com.sudo.common.enums.SysStatus;
import com.sudo.common.utils.HttpUserInfoUtil;
import com.sudo.common.utils.JsonRes;
import com.sudo.common.utils.JsonUtil;
import com.sudo.common.utils.RetResponse;
import com.sudo.dao.admin.model.dto.OnlineUserDTO;
import com.sudo.service.admin.service.AdminBaseService;
import com.sudo.service.admin.service.SysRedisAuthService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * author：为道日损 2020-04-24 17:35
 */
@Order(10)
@Component
public class UserTokenInterceptor extends AdminBaseService implements HandlerInterceptor {
    @Resource
    private SysRedisAuthService sysRedisAuthService;
    /**
     * 请求controller之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        String username = HttpUserInfoUtil.getSessionUser(request);
        if (StringUtils.isBlank(username)) {
            RetResponse.res(response, JsonRes.errorMsg("该用户不存在"));
            return false;
        }
        String userToken = HttpUserInfoUtil.getSessionToken(request);
        if (StringUtils.isBlank(userToken)) {
            RetResponse.res(response, JsonRes.errorMsg("该用户未登录"));
            return false;
        }

        String redisUserToken = sysRedisAuthService.getRedisUserTokenString(username);
        if (StringUtils.isBlank(redisUserToken)) {
            RetResponse.res(response, JsonRes.errorMsg("Token失效，请重新登录"));
            return false;
        }
        OnlineUserDTO onlineUserDTO = JsonUtil.jsonToPojo(redisUserToken, OnlineUserDTO.class);
        if (onlineUserDTO == null) {
            RetResponse.res(response, JsonRes.errorMsg("用户信息异常"));
            return false;
        }
        if (SysStatus.OFF.name().equals(onlineUserDTO.getStatus())) {
            RetResponse.res(response, JsonRes.errorMsg("当前用户已禁用"));
            return false;
        }
        String redisRoleStatus = sysRedisAuthService.getRedisRoleStatus(onlineUserDTO.getRoleCode());

        if (StringUtils.isBlank(redisRoleStatus)){
            RetResponse.res(response, JsonRes.errorMsg("该用户对应角色不存在"));
            return false;
        }
        if (!SysStatus.ON.name().equals(redisRoleStatus)) {
            RetResponse.res(response, JsonRes.errorMsg("该用户对应角色已禁用"));
            return false;
        }

        if (!onlineUserDTO.getToken().equals(userToken)) {
            RetResponse.res(response, JsonRes.errorMsg("账号可能在异地登录"));
            return false;
        }
        /*
         * false：请求被拦截，被驳回，验证出现问题
         * true：请求验证校验ok，可以放行
         */
        sysRedisAuthService.setRedisUserExpire(username);
        return true;
    }

}
